<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="你知道一个类是如何加载的吗, Gtwff">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id="></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', '');
</script>


    <title>你知道一个类是如何加载的吗 | Gtwff</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Gtwff</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Gtwff</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/kuangty/kuangty" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/kuangty/kuangty" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/23.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">你知道一个类是如何加载的吗</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%AD%90%E7%B3%BB%E7%BB%9F/">
                                <span class="chip bg-color">JVM 类加载子系统</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/JVM/" class="post-category">
                                JVM
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-10-30
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-03-27
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.1k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    10 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="类加载子系统"><a href="#类加载子系统" class="headerlink" title="类加载子系统"></a>类加载子系统</h1><h2 id="一、内存结构概述"><a href="#一、内存结构概述" class="headerlink" title="一、内存结构概述"></a>一、内存结构概述</h2><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327114957141.png" alt="image-20220327114957141" style="zoom:80%;" />

<h2 id="二、类加载器与类的加载过程"><a href="#二、类加载器与类的加载过程" class="headerlink" title="二、类加载器与类的加载过程"></a>二、类加载器与类的加载过程</h2><h3 id="一、类加载器子系统作用"><a href="#一、类加载器子系统作用" class="headerlink" title="一、类加载器子系统作用"></a>一、类加载器子系统作用</h3><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115004599.png" alt="image-20220327115004599" style="zoom:80%;" />

<ul>
<li>类加载器子系统负责从文件系统或者网络中加载class文件，class文件在文件开头有特定的文件标识。</li>
<li><code>CLassLoader</code>只负责class文件的加载，至于他是否可以运行，则由Execution Engine决定。</li>
<li>加载的类信息存放于一块称为方法区的内存空间。除了类的信息外，方法区中还会存放运行时常量池信息，可能还包括字符串字面量和数字常量（这部分信息是 Class 文件中常量池部分的内存映射）。</li>
</ul>
<h3 id="二、类加载器ClassLoader角色"><a href="#二、类加载器ClassLoader角色" class="headerlink" title="二、类加载器ClassLoader角色"></a>二、类加载器<code>ClassLoader</code>角色</h3><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115011248.png" alt="image-20220327115011248" style="zoom:80%;" />

<ul>
<li>class file 存在于本硬盘上，可以理解为设计师画在纸上的模板，而最终这个模板在执行的时候是要加载到<code>JVM</code>当中来根据这个文件实例化出n个一模一样的实例。</li>
<li>class file 加载到<code>JVM</code>中，被称为DNA元数据模板，放在方法区。</li>
<li>在 .class 文件 -&gt;  <code>JVM</code> -&gt; 最终成为元数据模板，此过程就一定要一个运输工具（类装载器 <code>ClassLoader</code>），扮演一个快递员的角色。</li>
</ul>
<h3 id="三、类的加载过程"><a href="#三、类的加载过程" class="headerlink" title="三、类的加载过程"></a>三、类的加载过程</h3><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115017597.png" alt="image-20220327115017597" style="zoom:80%;" />

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115022429.png" alt="image-20220327115022429" style="zoom:80%;" />

<ul>
<li><p>加载：</p>
<ul>
<li>通过一个类的全限定名获取定义此类的二进制字节流</li>
<li>将这个字节流所代表的静态存储结构转化为方法区的运行时数据结构</li>
<li>在内存中生成一个代表这个类的<code>java.lang.Class</code>对象，作为方法区这个类的各种数据的访问入口。</li>
</ul>
</li>
<li><p>补充：加载.class 文件的方式</p>
<ul>
<li>从本地系统中直接加载</li>
<li>通过网络获取，典型场景：Web Applet</li>
<li>从zip压缩包中读取，成为日后jar、war格式的基础</li>
<li>运行时计算生成，使用最多的是：动态代理技术</li>
<li>由其它文件生成，典型场景：<code>JSP</code>应用</li>
<li>从专有数据库中提取.class 文件，比较少见</li>
<li>从加密文件中获取，典型的防Class文件被反编译的保护措施。</li>
</ul>
</li>
<li><p>链接：</p>
<ul>
<li>验证(Verify) ：<ul>
<li>目的在于确保Class文件的字节流中包含信息符合当前虚拟机要求，保证被加载的类的正确性，不会危害虚拟机自身的安全。</li>
<li>主要包括四种验证，文件格式验证，元数据验证，字节码验证，符号引用验证。</li>
</ul>
</li>
<li>准备（Prepare）：<ul>
<li>为类变量分配内存并且设置该类变量的默认初始值，即零值。</li>
<li>这里不包括用final修饰的<code>static</code>，因为final在编译的时候就会被分配了，准备阶段会显式初始化。</li>
<li>这里不会为实例变量分配初始化，类变量会分配在方法区中，而实例变量是会随着对象一起分配到Java堆中。</li>
</ul>
</li>
<li>解析（Resolve）：<ul>
<li>将常量池内的符号引用转换为直接引用的过程。</li>
<li>事实上，解析操作往往会伴随着<code>JVM</code>在执行完初始化之后再执行。</li>
<li>符号引用就是一组符号来描述所引用的目标。符号引用的字面量形式明确定义在《<code>java</code>虚拟机规范》的class文件格式中。直接引用就是直接指向目标的指针、相对偏移量或一个间接定位到目标的句柄。</li>
<li>解析动作主要针对类或接口、字段、类方法、接口方法、方法类型等。对应常量池中的<code>CONSTANT_Class_info</code>、<code>CONSTANT_Fieldref_info</code>、<code>CONSTANT_Nethodref_info</code> 等。</li>
</ul>
</li>
</ul>
</li>
<li><p>初始化：</p>
<ul>
<li>初始化阶段就是执行类构造器方法<clinit>() 的过程。</li>
<li>此方法不需定义，是<code>javac</code>编译器自动收集类中的所有类变量的赋值动作和静态代码块中的语句合并而来。</li>
<li>构造器方法中指令按语句在源文件中出现的顺序执行。</li>
<li><client>() 不同于类的构造器。（关联：构造器是虚拟机视角下的<init>())</li>
<li>若该类具有父类，<code>JVM</code>会保证子类的<clinit>（）执行前，父类的<client>()已经执行完毕。</li>
<li>虚拟机必须保证一个类的<clinit>() 方法在多线程下被同步加锁。</li>
</ul>
</li>
</ul>
<h2 id="三、类加载器分类"><a href="#三、类加载器分类" class="headerlink" title="三、类加载器分类"></a>三、类加载器分类</h2><h3 id="一、类加载器分类"><a href="#一、类加载器分类" class="headerlink" title="一、类加载器分类"></a>一、类加载器分类</h3><ul>
<li><code>JVM</code>支持两种类型的类加载器，分别为引导类加载器（<code>Bootstrap ClassLoader</code>）和自定义类加载器（<code>User-Defined ClassLoader</code>）。</li>
<li>从概念上来讲，自定义类加载器一般指的是程序中由开发人员自定义的一类类加载器，但是Java虚拟机规范却没有这么定义，而是将所有派生于抽象类<code>ClassLoader</code>的类加载器都换为自定义类加载器。</li>
<li>无论类加载器的类型如何划分，在程序中我们最常见的类加载器始终只有3个，如下所示：</li>
</ul>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115029890.png" alt="image-20220327115029890" style="zoom:80%;" />

<blockquote>
<p>这里四者之间的关系是包含关系。而不是上层下层，也不是父类的继承关系。</p>
</blockquote>
<ul>
<li><p><input checked="" disabled="" type="checkbox">  虚拟机自带的类加载器：</p>
</li>
<li><p>启动类加载器（引导类加载器， <code>Bootstrap ClassLoader</code>)</p>
<ul>
<li>这个类使用<code>C/C++</code>语言实现的，嵌套在<code>JVM</code>内部）。</li>
<li>它用来加载Java的核心库（<code>JAVA_HOME/jre/lib/rt.jar</code>、<code>resources.jar</code>或<code>sun.boot.class.path</code>路径下的内容），用于提供<code>JVM</code>自身需要的类。</li>
<li>并不继承自<code>java.lang.ClassLoader</code>，没有父加载器。</li>
<li>加载扩展类和应用程序类加载器，并指定为他们的父类加载器。</li>
<li>出于安全考虑，<code>Bootstrap</code>启动类加载器只加载包名为<code>java</code>、<code>javax</code>、<code>sun</code>等开头的类。</li>
</ul>
</li>
<li><p>扩展类加载器（<code>Extension ClassLoader</code>）</p>
<ul>
<li>Java语言编写，由<code>sun.misc.Launcher$ExtClassLoader</code>实现。</li>
<li>派生于<code>ClassLoader</code>类。</li>
<li>父类加载器为启动类加载器。</li>
<li>从<code>java.ext.dirs</code>系统属性所指定的目录中加载类库，或从<code>JDK</code>的安装目录的<code>jre/lib/ext</code>子目录（扩展目录）下加载类库。如果用户创建的<code>JAR</code>放在此目录下，也会自动由扩展类加载器加载。</li>
</ul>
</li>
<li><p>应用程序类加载器（系统类加载器，<code>AppClassLoader</code>)</p>
<ul>
<li><p><code>java</code>语言编写，由<code>sun.misc.Launcher$AppClassLoader</code>实现。</p>
</li>
<li><p>派生于 <code>ClassLoader</code>类。</p>
</li>
<li><p>父类加载器为扩展类加载器</p>
</li>
<li><p>它负责加载环境变量<code>classpath</code>或系统属性 <code>java.class.path</code>指定路径下的类库。</p>
<p>该类加载是程序中默认的类加载器，一般来说，Java应用的类都是由它来完成加载。</p>
</li>
<li><p>通过<code>ClassLoader#getSystemClassLoader（）</code>方法可以获取到该类加载器</p>
</li>
</ul>
</li>
<li><p>用户自定义类加载器</p>
<ul>
<li>用Java的日常应用程序开发中，类的加载几乎是由上述3类种加载器相互配合执行的，在必要时，我们还可以自定义类加载器，来定制类的加载方式。</li>
</ul>
</li>
</ul>
<blockquote>
<p>为什么要自定义类的加载器？</p>
<p>​    隔离加载类</p>
<p>​    修改类记载的方式</p>
<p>​    扩展加载源</p>
<p>​    防止源码泄露</p>
</blockquote>
<ul>
<li><p>用户自定义类加载器实现步骤：</p>
<ul>
<li>开发人员可以通过继承抽象类<code>java.lang.ClassLoader</code>类的方式，实现自己的类加载器，以满足一些特殊的需求。</li>
<li>在<code>JDK1.2</code>之前，在自定义类加载器时，总会去继承<code>ClassLoader</code>类并重写<code>loadClass（）</code>方法，从而实现自定义的类加载类，但是在<code>JDK1.2</code>之后已不再建议用户区覆盖<code>loadClass（）</code> 方法，而是建议把自己的类加载逻辑写在<code>findClass（）</code>方法中。</li>
<li>在编写自定义类加载器时，如果没有过于复杂的需求，可以直接继承<code>URLClassLoader</code>类，这样就可以避免自己去编写<code>findClass（）</code>方法以及其获取字节流的方式，使自定义类加载器编写更加简洁。</li>
</ul>
</li>
</ul>
<h3 id="二、关于ClassLoader"><a href="#二、关于ClassLoader" class="headerlink" title="二、关于ClassLoader"></a>二、关于<code>ClassLoader</code></h3><ul>
<li><code>ClassLoader</code>类，它是一个抽象类，其后所有的类加载器都继承自<code>ClassLoader</code>（不包括启动类加载器）</li>
</ul>
<table>
<thead>
<tr>
<th>方法名称</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>getParent()</code></td>
<td>返回该类加载器的超类加载器</td>
</tr>
<tr>
<td><code>laodClass(String name)</code></td>
<td>加载名称为name的类，返回结果为<code>java.lang.Class</code>类的实例</td>
</tr>
<tr>
<td><code>findClass(String name)</code></td>
<td>查找名称为name的类，返回结果为<code>java.lang.Class</code>类的实例</td>
</tr>
<tr>
<td><code>findLoadedClass(String name)</code></td>
<td>查找名称为name的已经被加载过的类，返回结果为<code>java.lang.Class</code>类的实例</td>
</tr>
<tr>
<td><code>defineClass(String name, byte[] n, int off, int len)</code></td>
<td>把字节数组b中的内容转换为一个Java类，返回结果为<code>java.lang.Class</code>类的实例</td>
</tr>
<tr>
<td><code>resolveClass(Class&lt;?&gt; c)</code></td>
<td>连接指定的一个Java类</td>
</tr>
</tbody></table>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115037611.png" alt="image-20220327115037611" style="zoom:80%;" />

<blockquote>
<p><code>sun.misc.Launcher</code>它是一个<code>java</code>虚拟机的入口应用</p>
</blockquote>
<h3 id="三、获取CLassLoader的途径"><a href="#三、获取CLassLoader的途径" class="headerlink" title="三、获取CLassLoader的途径"></a>三、获取<code>CLassLoader</code>的途径</h3><ul>
<li>方式一：获取当前类的<code>ClassLoader</code><ul>
<li><code>clazz.getClassLoader( )</code></li>
</ul>
</li>
<li>方式二：获取当前线程上下文的<code>ClassLoader</code><ul>
<li><code>Thread.currentThread().getContextClassLoader()</code></li>
</ul>
</li>
<li>方式三：获取系统的<code>ClassLoader</code><ul>
<li><code>ClassLoader.getSystemClassLoader()</code></li>
</ul>
</li>
<li>方式四：获取调用者的<code>ClassLoader</code><ul>
<li><code>DriverManager.getCallerClassLoader()</code></li>
</ul>
</li>
</ul>
<h2 id="四、双亲委派机制"><a href="#四、双亲委派机制" class="headerlink" title="四、双亲委派机制"></a>四、双亲委派机制</h2><h3 id="一、双亲委派机制"><a href="#一、双亲委派机制" class="headerlink" title="一、双亲委派机制"></a>一、双亲委派机制</h3><ul>
<li><p>Java虚拟机对class文件采用的是按需加载的方式，也就是说当需要使用该类时才会将它的class文件加载到内存生成class对象。而且加载某个类的class文件时，Java虚拟机采用的是双亲委派模式，即把请求交由父类处理，他是一种任务委派模式。</p>
</li>
<li><p>工作原理：</p>
<ul>
<li>如果一个类加载器收到了类加载请求，它并不会自己 先去加载，而是把这个请求委托给父类加载器去执行；</li>
<li>如果父类加载器还存在其他父类加载器，则进一步向上委托，依次递归，请求最终将到达顶层的启动类加载器。</li>
<li>如果父类加载器可以完成类加载任务，就成功返回，倘若父加载器无法完成此加载任务，子加载器才会尝试自己去加载，这就是双亲委派模式。</li>
</ul>
</li>
</ul>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115043832.png" alt="image-20220327115043832" style="zoom:80%;" />

<h3 id="二、双亲委派机制举例"><a href="#二、双亲委派机制举例" class="headerlink" title="二、双亲委派机制举例"></a>二、双亲委派机制举例</h3><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327115049493.png" alt="image-20220327115049493" style="zoom:80%;" />

<h3 id="三、双亲委派机制优势"><a href="#三、双亲委派机制优势" class="headerlink" title="三、双亲委派机制优势"></a>三、双亲委派机制优势</h3><ul>
<li>避免类的重复加载</li>
<li>保护程序安全，防止核心<code>API</code>被随意篡改<ul>
<li>自定义类：<code>java.lang.String</code></li>
<li>自定义类：<code>java.lang.ShkStart</code></li>
</ul>
</li>
</ul>
<blockquote>
<p><code>java.lang.SecurityException: Prohibited package name：java.lang</code></p>
</blockquote>
<h3 id="四、沙箱安全机制"><a href="#四、沙箱安全机制" class="headerlink" title="四、沙箱安全机制"></a>四、沙箱安全机制</h3><ul>
<li>自定义String类，但是在加载自定义String类的时候会率先使用引导类加载器加载，而引导类加载器在加载的过程中会先加载<code>jdk</code>自带的文件(<code>rt.jar</code>包中<code>java\lang\Sttring.class</code>)，报错信息说没有main方法，就是因为加载的是<code>rt.jar</code>包中的String类。这样可以保证对<code>java</code>核心源代码的保护，这就是沙箱安全机制。</li>
</ul>
<h2 id="五、其他"><a href="#五、其他" class="headerlink" title="五、其他"></a>五、其他</h2><ul>
<li>在<code>JVM</code>中表示两个Class对象是否为同一个存在两个必要条件：<ul>
<li>类的完整类名必须一致，包括包名。</li>
<li>加载这个类的<code>classLoader</code>（指<code>classLoader</code>实例对象）必须相同）。</li>
</ul>
</li>
<li>换句话说，在<code>JVM</code>中，即使这两个类对象（class对象）来源于同一个Class文件，被同一个虚拟机所加载，但只要加载它们的<code>ClassLoader</code>实例对象不同，那么这两个类对象也是不相等的。</li>
</ul>
<h3 id="一、对类加载器的引用"><a href="#一、对类加载器的引用" class="headerlink" title="一、对类加载器的引用"></a>一、对类加载器的引用</h3><ul>
<li>知道一个类型是由启动加载器加载的还是由用户类加载器加载的。如果一个类型是由用户类加载器加载的，那么<code>JVM</code>会将这个类加载器的同一个引用作为类型信息的一部分保存在方法区中。当解析一个类型到另一个类型的引用的时候，<code>JVM</code>需要`保证这两个类型的类加载器是相同的。</li>
</ul>
<h3 id="二、类的主动使用和被动使用"><a href="#二、类的主动使用和被动使用" class="headerlink" title="二、类的主动使用和被动使用"></a>二、类的主动使用和被动使用</h3><p>Java程序对类的使用方式分为：主动使用和被动使用。</p>
<ul>
<li>主动使用，又分为七种情况：<ul>
<li>创建类的实例</li>
<li>访问某个类或接口的静态变量，或者对该静态变量赋值。</li>
<li>调用类的静态方法</li>
<li>反射（比如：<code>Class.forName（“com.Test&quot;)</code>)</li>
<li>初始化一个类的子类</li>
<li>Java虚拟机启动时被标明为启动类的类</li>
<li><code>JDK7</code>开始提供的动态语言支持：<ul>
<li><code>java.lang.invoke.MethodHandle</code>实例的解析结果</li>
<li><code>REF_getStatic</code>、<code>REF_putStatic</code>、<code>REF_invokeStatic</code>句柄对应的类没有初始化，则初始化。</li>
</ul>
</li>
</ul>
</li>
<li>除了以上7种情况，其他使用Java类的方式都被看做是对类的被动使用，都不会导致类的初始化。</li>
</ul>
<blockquote>
<p>巨人的肩膀：</p>
<p>尚硅谷 JVM</p>
</blockquote>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Gtwff</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://kuangty.gitee.io/2021/10/30/JVM/JVM%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%AD%90%E7%B3%BB%E7%BB%9F/">https://kuangty.gitee.io/2021/10/30/JVM/JVM%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%AD%90%E7%B3%BB%E7%BB%9F/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Gtwff</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%AD%90%E7%B3%BB%E7%BB%9F/">
                                    <span class="chip bg-color">JVM 类加载子系统</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/10/30/%E5%85%AB%E8%82%A1%E6%96%87/%E9%9D%A2%E8%AF%95%E9%A2%98%E6%B1%87%E6%80%BB/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/18.jpg" class="responsive-img" alt="杰哥，你的八股文">
                        
                        <span class="card-title">杰哥，你的八股文</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-10-30
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%85%AB%E8%82%A1%E6%96%87/" class="post-category">
                                    八股文
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E9%9D%A2%E8%AF%95%E9%A2%98/">
                        <span class="chip bg-color">面试题</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/10/30/Redis/Redis_%E4%B8%BB%E4%BB%8E%E5%BA%93%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E6%95%B0%E6%8D%AE%E4%B8%80%E8%87%B4/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/20.jpg" class="responsive-img" alt="你知道 Redis 如何实现主从一致吗">
                        
                        <span class="card-title">你知道 Redis 如何实现主从一致吗</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-10-30
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Redis/" class="post-category">
                                    Redis
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Redis-%E4%B8%BB%E4%BB%8E%E4%B8%80%E8%87%B4%E6%80%A7/">
                        <span class="chip bg-color">Redis 主从一致性</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2022</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Gtwff</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">577.4k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2019";
                        var startMonth = "6";
                        var startDate = "28";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/kuangtianyu" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1575235124@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1575235124" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1575235124" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/kuang-tian-yu-59" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/kuang-tian-yu-59" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
